package com.data.mall.utils.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;

/**
 * @author xiaomai
 */
@Getter
@Setter
@Slf4j
public class Response<T> implements Serializable {

    private static final long serialVersionUID = 6686419048438176898L;

    private int error;

    private String message;

    private T body;

    private Response() {
    }

    private Response(int code, String message, T body) {
        this.error = code;
        this.message = message;
        this.body = body;
    }

    public static <T> Response getInstance() {
        Response response = new Response();
        response.setError(0);
        return response;
    }

    public static <T> Response getInstance(T body) {
        Response response = new Response();
        response.setError(0);
        response.setBody(body);
        return response;
    }

    public static <T> Response getInstance(int code, String message) {
        Response response = new Response();
        response.setError(code);
        response.setMessage(message);
        return response;
    }

    public Response<T> error(int error) {
        this.setError(error);
        return this;
    }

    public Response<T> body(T body) {
        this.setBody(body);
        return this;
    }

    public Response message(String message) {
        this.setMessage(message);
        return this;
    }

    public static Response ok() {
        return Response.getInstance();
    }

    public static Response nonExpect(int error) {
        return getInstance().error(error);
    }

    public Boolean hasError() {
        return this.error != 0;
    }

    @Override
    public String toString() {
        if (null == this.body) {
            this.body((T) new JSONObject());
        }
        return JSON.toJSONString(this);
    }
}
